package manager.categories.service.impl;
import common.SnowflakeIdWorker;
import manager.categories.dao.CategoryDao;
import manager.categories.service.CategoryService;
import manager.categories.vo.CategoryEnum;
import manager.categories.vo.CategoryVO;
import manager.feign.ProductCategoryThirdService;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service(value = "categoryService")
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private ProductCategoryThirdService productCategoryThirdService;
//    @Cacheable(value ="_categoryVOCacheKey")
    @Override
    public List<CategoryVO> selectByCondition(CategoryVO categoryVO) {
        List<CategoryVO> allCatagories=categoryDao.selectByCondition(categoryVO);
        //找到
        List<CategoryVO> fatherCategories = allCatagories.stream().filter(
                category -> CategoryEnum.LEVEL_ONE.getValue().equals(category.getParentId())
        ).collect(Collectors.toList());
        List<CategoryVO> categories=new ArrayList<CategoryVO>();
        fatherCategories.forEach(item->{
            this.addChildrenNodeToList(categories,allCatagories,item);
        });
        return fatherCategories;
    }
    private void addChildrenNodeToList(List<CategoryVO> categories,List<CategoryVO> allCategories,CategoryVO currentNode){
        //获取以当前节点为父亲的所有节点
        List<CategoryVO> childrenNodes=allCategories.stream().filter(item->item.getParentId().equals(currentNode.getId())).collect(Collectors.toList());
        if(childrenNodes.size()>0){
            currentNode.setChildren(childrenNodes);
            childrenNodes.forEach(childItem->{
                addChildrenNodeToList(categories,allCategories,childItem);
            });
        }
    }

    @Override
    public void addCategory(CategoryVO categoryVO) {
        categoryDao.addCategory(categoryVO);
    }

    @Override
    public void updateCategory(CategoryVO categoryVO) {
        categoryDao.updateCategory(categoryVO);
    }

    @Override
    public void deleteCategories(Integer[] ids) {
        categoryDao.deleteCategories(ids);
    }

    @Override
    public void getJdCategory() throws JSONException {
            String  objectStr=productCategoryThirdService.getCategoryData();
            String jsonStr=objectStr.substring(20,objectStr.length()-1);
            JSONObject jsonObject = new JSONObject(jsonStr);
            JSONArray data=(JSONArray)jsonObject.get("data");
            List<Map<String,Object>> category=new ArrayList<Map<String,Object>>();
            buildCategoryData(data,category);
            SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
            List<CategoryVO> categoryList=new ArrayList<>();
            List<CategoryVO> insertData=this.getInsertCategorys(category,categoryList,idWorker);
            Integer[] array = new Integer[0];
            categoryDao.deleteCategories(array);
            categoryDao.addCategoryBatch(insertData);
    }
    private List<CategoryVO> getInsertCategorys(List<Map<String,Object>> category, List<CategoryVO> categoryList, SnowflakeIdWorker idWorker){
           category.forEach(item->{
                CategoryVO categoryVO=new CategoryVO();
                String id=String.valueOf(idWorker.nextId());
                categoryVO.setId(id);
                categoryVO.setParentId("0");
                categoryVO.setName(item.get("name").toString());
                List<Map<String,Object>> children=(List<Map<String,Object>>)item.get("children");
                if(children!=null&&children.size()>0){
                    insertChildrenCategorys(children,categoryList,id,idWorker);
                }
                categoryList.add(categoryVO);
           });
           return categoryList;
    }
    private void insertChildrenCategorys(List<Map<String,Object>> category, List<CategoryVO> categoryList, String parentId, SnowflakeIdWorker childrenIdWorker){
        category.forEach(item->{
            Long id=childrenIdWorker.nextId();
            CategoryVO categoryVO=new CategoryVO();
            categoryVO.setId(String.valueOf(id));
            categoryVO.setParentId(parentId);
            categoryVO.setName(item.get("name").toString());
            categoryVO.setSort(item.get("categoryIds").toString());
            List<Map<String,Object>> children=(List<Map<String,Object>>)item.get("children");
            if(children!=null&&children.size()>0){
                insertChildrenCategorys(children,categoryList,String.valueOf(id),childrenIdWorker);
            }
            categoryList.add(categoryVO);
        });
    }
    //构造一级分类
    private void buildCategoryData(JSONArray data,List<Map<String,Object>> category)throws JSONException{
            //获取分类
            for(int i=0;i<data.length();i++){
                Map<String,Object> map=new HashMap<String,Object>();
                JSONObject dataItem=(JSONObject)data.get(i);
                JSONArray s=(JSONArray)dataItem.get("s");
                StringBuffer stringBuffer=new StringBuffer();
                for(int j=0;j<s.length();j++){
                    JSONObject sobj=(JSONObject)s.get(j);
                    String name=(String)sobj.get("n");
                    int pos=name.indexOf("|");
                    String subName=name.substring(pos+1,name.length()-3);
                    stringBuffer.append(subName);
                    stringBuffer.append("/");
                }
                map.put("name",stringBuffer.substring(0,stringBuffer.length()-1).toString());
                JSONObject sobj=(JSONObject)s.get(0);
                List<Map<String,Object>> childrenCategory=new ArrayList<Map<String,Object>>();
                JSONArray childrenArray=(JSONArray)sobj.get("s");
                if(childrenArray.length()>0){
                    buildChildrenCategoryData(childrenArray,childrenCategory);
                }
                map.put("children",childrenCategory);
                category.add(map);
            }
    }
    private void buildChildrenCategoryData(JSONArray data,List<Map<String,Object>> category)throws JSONException{
        //获取分类
        for(int i=0;i<data.length();i++){
            Map<String,Object> map=new HashMap<String,Object>();
            JSONObject dataItem=(JSONObject)data.get(i);
            String name=(String)dataItem.get("n");
            int pos=name.indexOf("|");
            String subName=name.substring(pos+1,name.length()-3);
            StringBuffer stringBuffer=new StringBuffer();
            stringBuffer.append(subName);
            String categoryIds=getCategoryIds(name);
            map.put("name",stringBuffer);
            if(StringUtils.isNotBlank(categoryIds)){
                map.put("categoryIds",categoryIds);
            }else{
                String categorys=name.substring(0,pos);
                if(categorys.indexOf("-")>0){
                    map.put("categoryIds",categorys);
                }else{
                    map.put("categoryIds","");
                }
            }
            List<Map<String,Object>> childrenCategory=new ArrayList<Map<String,Object>>();
            map.put("children",childrenCategory);
            JSONArray childrenArray=(JSONArray)dataItem.get("s");
            if(childrenArray.length()>0){
                buildChildrenCategoryData(childrenArray,childrenCategory);
            }
            category.add(map);
        }
    }
    private String getCategoryIds(String categoryInfo){
        String pattern = "cat=.*?\\&";
        Pattern compile = Pattern.compile(pattern);
        Matcher m=compile.matcher(categoryInfo);
        String categoryIds="";
        while (m.find()){
            categoryIds=m.group();
        }
        if(StringUtils.isNotBlank(categoryIds)){
            return categoryIds.substring(4,categoryIds.length()-1).trim().replace("%2C","-").replace(",","-");
        }
        return "";
    }
}
